package com.gmrz.uap.datastatistics;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gmrz.uap.authmetadata.AuthMetadataService;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.AuthTypeInterceptor;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.common.DBCommon;
import com.gmrz.uap.common.UAPSSOHelper;
import com.gmrz.uap.dict.DictConst;
import com.gmrz.uap.dict.DictService;
import com.gmrz.uap.job.TaskConst;
import com.gmrz.uap.model.*;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.tenant.TenantService;
import com.gmrz.uap.util.DateUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import javax.servlet.http.Cookie;
import java.util.*;

public class DataStatisticsController extends ControllerSupport {
    public final static String STATISTICS_RESULT_KEY_ALL = "statistics_all";

    /**
     * 用户注册统计和注册环比统计
     */
    @Before(ResourceInterceptor.class)
    public void register() {
        Dict dict = new Dict();
        dict.setData2("1");//包含注册相关的认证类型
        dict.setDtId(DictConst.DICT_TYPE_STATICS_AUTH_AUTH_TYPE_ID);
        dict.setIsEnable("1");//是否启用
        List<Dict> authTypeList = DictService.me.getDictList(dict);
        setAttr("authTypeList", authTypeList);
    }


    /**
     * 用户认证统计
     */
    @Before(ResourceInterceptor.class)
    public void verify() {
        List<Dict> authTypeList = DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_STATICS_AUTH_AUTH_TYPE_ID);
        setAttr("authTypeList", authTypeList);
    }


    /**
     * 手机使用统计
     */
    @Before(ResourceInterceptor.class)
    public void phoneCount() {
        List<AuthMetadata> aaids = AuthMetadataService.me.findAll();
        setAttr("aaids", aaids);
    }


    /**
     * 用户注销统计
     */
    @Before(ResourceInterceptor.class)
    public void logout() {
        Dict dict = new Dict();
        dict.setData2("1");//包含注册相关的认证类型
        dict.setIsEnable("1");//是否启用
        dict.setDtId(DictConst.DICT_TYPE_STATICS_AUTH_AUTH_TYPE_ID);
        List<Dict> authTypeList = DictService.me.getDictList(dict);

        setAttr("authTypeList", authTypeList);
    }

    /**
     * 获取需要统计分析的年份
     */
    public void getStatisticsAllYears() {
        DateTime earliestDate = DataStatistics.dao.getEarliestDate();
        List<Integer> statisticsYears = DataStatisticsService.me.differYears(earliestDate.getYear());//获取相差的年数集合
        List<Map<String, Object>> comboboxValue = new ArrayList<Map<String, Object>>();

        for (int i = 0; i < statisticsYears.size(); i++) {
            result = new HashMap<String, Object>();
            result.put("id", statisticsYears.get(i));
            result.put("text", String.valueOf(statisticsYears.get(i)));

            if (i == statisticsYears.size()-1) {
                result.put("selected", true);
            }

            comboboxValue.add(result);
        }
        render(responseJsonRender(comboboxValue));
    }


    /**
     * 获取需要统计分析的租户
     */
    public void getStatisticsTenants() {
        List<Tenant> tenantList = TenantService.me.getAllTenants();
        List<Map<String, Object>> comboboxValue = new ArrayList<Map<String, Object>>();

        if (!tenantList.isEmpty()) {
            for (Tenant tenant : tenantList) {
                result = new HashMap<String, Object>();
                result.put("id", tenant.getTenantId());
                result.put("text", tenant.getAliasName());

                if (StrKit.equals(tenant.getTenantId(), getCookie(SystemConst.COOKIE_TENANT_ID))) {
                    result.put("selected", true);
                }

                comboboxValue.add(result);
            }
        }
        render(responseJsonRender(comboboxValue));
    }


    /**
     * 获取注册统计数据
     */
    public void regStatisticsCharts() {
        //需要统计的年份
        String staYear = getPara("staYear");
        //渠道名称
        String tenantId = this.getCookie(SystemConst.COOKIE_TENANT_ID);

        result = DataStatisticsService.me.regStatisticsCharts(staYear, tenantId);

        render(responseJsonRender(result));
    }


    /**
     * 获取注册环比统计数据
     */
    public void regCompareStatisticsCharts() {
        //需要统计的年份
        String staYear = getPara("staYear");

        //渠道名称
        String tenantId = this.getCookie(SystemConst.COOKIE_TENANT_ID);
        // 是否开启环比统计
        Dict dict =  DictService.me.findOneByName("ifsequential");

        result = DataStatisticsService.me.regCompareStatisticsCharts(staYear, tenantId);
        result.put("ifsequential",dict.getIsEnable());

        render(responseJsonRender(result));
    }


    /**
     * 获取注销统计数据
     */
    public void logoutStatisticsCharts() {
        //需要统计的年份
        String staYear = getPara("staYear");
        //渠道名称
        String tenantId = this.getCookie(SystemConst.COOKIE_TENANT_ID);

        result = DataStatisticsService.me.logoutStatistics(staYear, tenantId);

        render(responseJsonRender(result));
    }


    /**
     * 获取注销环比统计数据
     */
    public void logoutCompareStatisticsCharts() {
        //需要统计的年份
        String staYear = getPara("staYear");
        //渠道名称
        String tenantId = this.getCookie(SystemConst.COOKIE_TENANT_ID);
        // 环比统计是否开启
        Dict dict =  DictService.me.findOneByName("ifsequential");

        result = DataStatisticsService.me.logoutCompareStatisticsCharts(staYear, tenantId);
        result.put("ifsequential",dict.getIsEnable());
        render(responseJsonRender(result));
    }


    /**
     * 获取验证统计数据
     */
    public void verifyStatisticsCharts() {
        //需要统计的年份
        String staYear = getPara("staYear");
        //渠道名称
        String tenantId = this.getCookie(SystemConst.COOKIE_TENANT_ID);

        result = DataStatisticsService.me.verifyStatisticsCharts(staYear, tenantId);

        render(responseJsonRender(result));
    }


    /**
     * 获取手机使用统计数据
     */
    public void aaidStatisticsCharts() {
        //需要统计的年份
        String staYear = getPara("staYear");
        //渠道名称
        String tenantId = this.getCookie(SystemConst.COOKIE_TENANT_ID);

        //需要统计的认证器
        String aaidList = getPara("aaidList");
        // 反转义回去
        aaidList = StringEscapeUtils.unescapeHtml4(aaidList);
        JSONArray aaidJsonArray = JSON.parseArray(aaidList);

        List<List<Integer>> statisticsResult = new ArrayList<List<Integer>>();

        for (int j = 0; j < aaidJsonArray.size(); j++) {
            List<Integer> monthList = DataStatisticsService.me.getMonthForYear();//12个月的初始值
            DataStatistics dataStatistics = new DataStatistics();
            dataStatistics.setStaType(TaskConst.STATISTICS_KEY_AAID);//统计类型
            // 统计日期, 年，为了使用上索引，拼接成日期; staYear+ "-01-01" ： 2018-01-01
            dataStatistics.set(DBCommon.TABLE_DATA_STATISTICS_COLUMN_STA_DATE, staYear+ "-01-01");
            dataStatistics.set(DBCommon.TABLE_DATA_STATISTICS_COLUMN_STA_DATEOver, staYear+ "-12-31");
            dataStatistics.setTenantId(tenantId);//渠道名称
            dataStatistics.setAaid(aaidJsonArray.getString(j));

            //获取当前年份月度统计数据
            List<DataStatistics> statisticsDataList = DataStatistics.dao.getStatisticsCount(dataStatistics);

            for (int i = 0; i < statisticsDataList.size(); i++) {
                int month = new DateTime(statisticsDataList.get(i).getData1()).minusMonths(1).getMonthOfYear();
                if (month == 12) {
                    month = 0;
                }

                monthList.set(month, statisticsDataList.get(i).getStaCount());
            }

            statisticsResult.add(monthList);
        }

        render(responseJsonRender(statisticsResult));
    }

    /**
     * 获取统计分析年份集合
     */
    public void getStaYears() {
        //开始日期
        String startDate = getPara("startDate");

        //结束日期
        String endDate = getPara("endDate");

        List<Integer> statisticsYears = DataStatisticsService.me.getStaYears(startDate, endDate);

        if (statisticsYears.isEmpty()) {
            DateTime earliestDate = DataStatistics.dao.getEarliestDate();
            statisticsYears = DataStatisticsService.me.differYears(earliestDate.getYear());//获取相差的年数集合
        }
        render(responseJsonRender(statisticsYears));

    }

    /**
     * 注册年度统计
     */
    @Before(ResourceInterceptor.class)
    public void regYear() {
        setAttr("authTypeList", DataStatisticsService.me.getAuthTypes(Boolean.TRUE));
    }


    public void getRegYear() {
        //渠道名称
        String tenantId = getPara("tenantId", getCookie(SystemConst.COOKIE_TENANT_ID));

        //开始日期
        String startDate = getPara("startDate");

        //结束日期
        String endDate = getPara("endDate");

        //认证类型
        List<Dict> authTypeList = DataStatisticsService.me.getAuthTypes(Boolean.TRUE);

        //统计年份
        List<Integer> staYears = DataStatisticsService.me.getStaYears(startDate, endDate);

        result = DataStatisticsService.me.getStaYear(tenantId, staYears, authTypeList, TaskConst.STATISTICS_KEY_REGCOUNT);

        render(responseJsonRender(result));
    }


    /**
     * 认证年度统计
     */
    @Before(ResourceInterceptor.class)
    public void authYear() {
        setAttr("authTypeList", DataStatisticsService.me.getAuthTypes(Boolean.FALSE));
    }

    public void getAuthYear() {
        //渠道名称
        String tenantId = getPara("tenantId", getCookie(SystemConst.COOKIE_TENANT_ID));

        //开始日期
        String startDate = getPara("startDate");

        //结束日期
        String endDate = getPara("endDate");

        //认证类型
        List<Dict> authTypeList = DataStatisticsService.me.getAuthTypes(Boolean.FALSE);

        //统计年份
        List<Integer> staYears = DataStatisticsService.me.getStaYears(startDate, endDate);

        result = DataStatisticsService.me.getStaYear(tenantId, staYears, authTypeList, TaskConst.STATISTICS_KEY_VERIFY);

        render(responseJsonRender(result));
    }

    /**
     * 注销年度统计
     */
    @Before(ResourceInterceptor.class)
    public void logoutYear() {
        setAttr("authTypeList", DataStatisticsService.me.getAuthTypes(Boolean.TRUE));
    }

    public void getLogoutYear() {
        //渠道名称
        String tenantId = getPara("tenantId", getCookie(SystemConst.COOKIE_TENANT_ID));

        //开始日期
        String startDate = getPara("startDate");

        //结束日期
        String endDate = getPara("endDate");

        //认证类型
        List<Dict> authTypeList = DataStatisticsService.me.getAuthTypes(Boolean.TRUE);

        //统计年份
        List<Integer> staYears = DataStatisticsService.me.getStaYears(startDate, endDate);

        result = DataStatisticsService.me.getStaYear(tenantId, staYears, authTypeList, TaskConst.STATISTICS_KEY_LOGOUTCOUNT);

        render(responseJsonRender(result));
    }

    /**
     * 机型统计
     */
    @Before(ResourceInterceptor.class)
    public void phoneUse() {

    }


    public void phoneUseList() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "use_count");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        String tenantId = getPara("tenantId", getCookie(SystemConst.COOKIE_TENANT_ID));
        String startDate = getPara("startDate", null);
        String endDate = getPara("endDate", null);

        Page<Record> pages = DataStatisticsService.me.getPhoneUse(tenantId, startDate, endDate, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, pages.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, pages.getList());

        render(responseJsonRender(result));
    }

    @Before({ResourceInterceptor.class, AuthTypeInterceptor.class})
    public void staDay() {

    }

    /**
     *  日统计数据
     */
    public void staDayList() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "sta_type");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        String tenantId = getPara("tenantId", getCookie(SystemConst.COOKIE_TENANT_ID));
        String staType = getPara("staType", null);
        String authType = getPara("authType", null);
        String startDate = getPara("startDate", null);
        String endDate = getPara("endDate", null);

        Page<DataStatistics> pages = DataStatisticsService.me.getStaDataForDay(tenantId, staType, authType, startDate, endDate, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, pages.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, pages.getList());

        render(responseJsonRender(result));
    }


    public void getSingleYearList() {
        render(responseJsonRender(DataStatisticsService.me.getSingleYearList()));
    }

    /**
     * 证书注册统计
     */
    @Before({ResourceInterceptor.class, AuthTypeInterceptor.class})
    public void certRegister() {
        User user = UAPSSOHelper.getUserByUapSessionId(getRequest());
        user = User.dao.findById(user.getUserId());

        List<String> tenantStrList = new ArrayList<String>();
        List<Tenant> tenantList;//如果用户为超级管理员则看到所有的渠道，渠道管理员则可以被分配的渠道
        if (StringUtils.isBlank(user.getTenantId())) {
            tenantList = TenantService.me.getAllTenants();

            String str = "<option value=\"ALL\" selected>全部</option>";
            tenantStrList.add(str);

            for(Tenant tenant : tenantList){
                tenantStrList.add("<option value=\""+tenant.getTenantId()+"\">"+tenant.getAliasName()+"</option>");
            }
        } else {
            tenantList = TenantService.me.getAllTenants(user.getTenantId());
            for(int i =0; i < tenantList.size(); i++){
                Tenant tenant = tenantList.get(i);
                if(i == 0){
                    tenantStrList.add("<option value=\""+tenant.getTenantId()+"\" selected>"+tenant.getAliasName()+"</option>");
                }else {
                    tenantStrList.add("<option value=\"" + tenant.getTenantId() + "\">" + tenant.getAliasName() + "</option>");
                }
            }
        }
        setAttr("tenants", tenantStrList);
        setAttr("startDate", DateUtil.getToday());
        setAttr("endDate", DateUtil.getToday());

        List<String> deviceTypeAliaslList = Devices.dao.getDeviceTypeAliasList();
        setAttr("deviceTypes", deviceTypeAliaslList);
    }

    public void getDeviceNameAliasList(){
        String deviceTypeAlias = getPara("deviceTypeAlias", null);
        if(null != deviceTypeAlias && !"".equals(deviceTypeAlias.trim())){
            List<Map<String,String>> resultList = new ArrayList<Map<String, String>>();
            Map<String,String> m = new HashMap<String, String>();
            m.put("deviceNameAlias","ALL");
            m.put("deviceNameAliasDesc","全部");
            resultList.add(m);
            List<String> deviceNameAliaslList = Devices.dao.getDeviceNameAliasList(deviceTypeAlias);
            //result.put("deviceNames", deviceNameAliaslList);
            for(String d : deviceNameAliaslList){
                m = new HashMap<String, String>();
                m.put("deviceNameAlias",d);
                m.put("deviceNameAliasDesc",d);
                resultList.add(m);
            }
            render(responseJsonRender(resultList));
        }
    }

    public void getCertRegister() {
        String date = DateUtil.getToday();
        DataStatisticsService.me.certDeviceTypeStatistics(new DateTime(date));

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "sta_type");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        String tenantId = getPara("tenantId", "ALL");
        String aaidType = getPara("aaidType", "SE");
        String deviceTypeAlias = getPara("deviceTypeAlias", "ALL");
        String deviceNameAlias = getPara("deviceNameAlias", "ALL");
        String startDate = getPara("startDate", null);
        String endDate = getPara("endDate", null);
        Dict dict = new Dict();
        dict.setDictText(aaidType);
        List<Dict> dictList = Dict.dao.getDictList(dict);
        List<String> aaidList = new ArrayList<String>();
        if(null != dictList){
            for(Dict d: dictList){
                aaidList.add(d.getDictName().trim());
            }
        }

        Page<Record> page1 = DataStatistics.dao.getCertRegister(tenantId,aaidList,deviceTypeAlias,deviceNameAlias,startDate, endDate, page, rows, sort, order);
        List<CertRegisterBean> list = new ArrayList<CertRegisterBean>();
        if(null != page1){
            List<Record> recordList = page1.getList();
            if(null != recordList){
                for(Record record : recordList){
                    String tenant_id = record.getStr("tenant_id");
                    String device_type_alias = record.getStr("device_type_alias");
                    String device_name_alias = record.getStr("device_name_alias");
                    int sta_count = record.getInt("sta_count");

                    if(null == device_type_alias || "".equals(device_type_alias.trim())){
                        device_type_alias = "其他";
                    }

                    if(null == device_name_alias || "".equals(device_name_alias.trim())){
                        device_name_alias = "其他";
                    }
                    CertRegisterBean certRegisterBean = new CertRegisterBean();
                    certRegisterBean.setAaid_type(aaidType);
                    certRegisterBean.setDevice_name(device_name_alias);
                    certRegisterBean.setDevice_type(device_type_alias);
                    certRegisterBean.setSta_count(sta_count);
                    certRegisterBean.setTenant_id(tenant_id);
                    list.add(certRegisterBean);
                }
            }
        }
        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, page1.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, list);
        render(responseJsonRender(result));
    }

    public void getOtherDeviceNameAliasList(){
        String tenantId = getPara("tenantId", "ALL");
        String aaidType = getPara("aaidType", "SE");
        String deviceTypeAlias = getPara("deviceTypeAlias", "ALL");
        String deviceNameAlias = getPara("deviceNameAlias", "ALL");
        String startDate = getPara("startDate", null);
        String endDate = getPara("endDate", null);
        Dict dict = new Dict();
        dict.setDictText(aaidType);
        List<Dict> dictList = Dict.dao.getDictList(dict);
        List<String> aaidList = new ArrayList<String>();
        if(null != dictList){
            for(Dict d: dictList){
                aaidList.add(d.getDictName().trim());
            }
        }
        List<Record> recordList = DataStatistics.dao.getOtherDeviceNameAliasList( tenantId, aaidList,  startDate,  endDate);
        List<CertRegisterBean> list = new ArrayList<CertRegisterBean>();
        if(null != recordList){
            for(Record record : recordList){
                String tenant_id = record.getStr("tenant_id");
                String device_type_alias = record.getStr("device_type");
                String device_name_alias = record.getStr("device_name");
                int sta_count = record.getInt("sta_count");

                if(null == device_type_alias || "".equals(device_type_alias.trim())){
                    device_type_alias = "其他";
                }

                if(null == device_name_alias || "".equals(device_name_alias.trim())){
                    device_name_alias = "其他";
                }
                CertRegisterBean certRegisterBean = new CertRegisterBean();
                certRegisterBean.setAaid_type(aaidType);
                certRegisterBean.setDevice_name(device_name_alias);
                certRegisterBean.setDevice_type(device_type_alias);
                certRegisterBean.setSta_count(sta_count);
                certRegisterBean.setTenant_id(tenant_id);
                list.add(certRegisterBean);
            }
        }
        render(responseJsonRender(list));
    }


    public void certUseCase() {
        render("certUseCase" + SystemConst.VIEW_EXTENDSION);
    }


    public void getCertUseCase(){
        String date = DateUtil.getToday();
        DataStatisticsService.me.certUseCaseStatistics(new DateTime(date));

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "inst_code");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        // 从缓存中取出用户信息
        User user = UAPSSOHelper.getUserByUapSessionId(getRequest());
        // 判断当前用户是否有权限
        boolean permissions = isTherePermissions();

        Page<Record> certUsePage = DataStatistics.dao.getCertUseCase(user.getInstCode(), permissions, page, rows);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, certUsePage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, certUsePage.getList());
        render(responseJsonRender(result));
    }


}
